package com.shengruan.admin.action;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;

import com.shengruan.admin.jdbc.SliderLogoJdbc;
import com.shengruan.admin.vo.SliderLogo;
import com.shengruan.common.BaseAction;
import com.shengruan.common.Constants;
 class SliderLogoAction extends BaseAction {

    private SliderLogoJdbc sliderLogoJdbc = (SliderLogoJdbc) this.getJdbc(SliderLogoJdbc.class);

    public void list() throws Exception {
        List<SliderLogo> sliderLogoList = this.sliderLogoJdbc.findAll();
        this.setRequest("sliderLogoList", sliderLogoList);
        this.forward("/admin/article/sliderLogo-list.jsp");
    }

    public void add() throws Exception {
        SliderLogo sliderLogo = new SliderLogo();

        //请求数据是不是使用multipart/form-data编码的
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		String imgName = "";
		if(isMultipart){
			// 创建一个文件上传的处理器
			ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
			try {
				// 使用处理器解析请求，获取到文件项的列表
				List items = upload.parseRequest(request);
				int size = items == null ? 0 : items.size();

				for(int i = 0; i < size; i++){ //处理每个文件项
					FileItem fileItem = (FileItem)items.get(i);
					if (fileItem.isFormField()) { //如果普通的表单域
						String name = fileItem.getFieldName();
					    String value = fileItem.getString();

                        if("title".equals(name)) sliderLogo.setTitle(new String(value.getBytes("iso-8859-1"), "UTF-8"));
                        if("url".equals(name)) sliderLogo.setUrl(new String(value.getBytes("iso-8859-1"), "UTF-8"));

                        System.out.println(name +"=" + new String(value.getBytes("iso-8859-1"), "UTF-8"));
				    } else { //表单文件域
				    	String fieldName = fileItem.getFieldName(); //文件域的名
				        String fileName = fileItem.getName(); //上传的文件名
                        if(StringUtils.isNotEmpty(fileName)) {
				        //String contentType = fileItem.getContentType(); //上传的文件类型
				        //long sizeInBytes = fileItem.getSize(); //上传的文件的大小字节数
				        //System.out.println("fieldname:" + fieldName);
				        //System.out.println("fileName:" + fileName);
				        //System.out.println("contentType:" + contentType);
				        //System.out.println("sizeInBytes:" + sizeInBytes);

                        //获取文件存放目录的全路径名
                        String basePath= request.getSession().getServletContext().getRealPath("uploadfiles/SliderLogo");
                        //System.out.println("上传文件的存放路径："+ basePath);
				        //把文件写到目的地
				        //File fullFile = new File(fileName.getName());
				        String suffix = fileName.substring(fileName.lastIndexOf("."));
				        imgName = generateFileName() + suffix;
				        File uploadedFile = new File(basePath, imgName);
				        fileItem.write(uploadedFile);

                        sliderLogo.setPic(imgName);
                        }
                    }
				}
				System.out.println("上传成功!!!");

			} catch (FileUploadException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}

            sliderLogo.setStatus(Constants.STATUS_INACTIVE);
            sliderLogo.setCreationTime(System.currentTimeMillis());
            this.sliderLogoJdbc.save(sliderLogo);

            /** 首页滑动Logo初始化 */
            Constants.sliderLogoList = sliderLogoJdbc.findAll(Constants.STATUS_ACTIVE);

            this.setRequest(Constants.MESSAGE, "添加滑动Logo成功。");
            this.redirect("/admin/article/sliderLogo-list.ac");
        }    
    }


    public void getById() throws Exception {
        String id = this.input("id");
        SliderLogo sliderLogo = this.sliderLogoJdbc.getById(Integer.valueOf(id));
        this.setRequest("sliderLogo", sliderLogo);
        this.forward("/admin/article/sliderLogo-edit.jsp");
    }

    public void edit() throws Exception {
        SliderLogo sliderLogo = null;

        //请求数据是不是使用multipart/form-data编码的
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		String imgName = "";
		if(isMultipart){
			// 创建一个文件上传的处理器
			ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
			try {
				// 使用处理器解析请求，获取到文件项的列表
				List items = upload.parseRequest(request);
				int size = items == null ? 0 : items.size();

				for(int i = 0; i < size; i++){ //处理每个文件项
					FileItem fileItem = (FileItem)items.get(i);
					if (fileItem.isFormField()) { //如果普通的表单域
						String name = fileItem.getFieldName();
					    String value = fileItem.getString();

                        if("id".equals(name))  sliderLogo = this.sliderLogoJdbc.getById(Integer.valueOf(value));
                        if("title".equals(name)) sliderLogo.setTitle(new String(value.getBytes("iso-8859-1"), "UTF-8"));
                        if("url".equals(name)) sliderLogo.setUrl(new String(value.getBytes("iso-8859-1"), "UTF-8"));

                        System.out.println(name +"=" + new String(value.getBytes("iso-8859-1"), "UTF-8"));
				    } else { //表单文件域
				    	String fieldName = fileItem.getFieldName(); //文件域的名
				        String fileName = fileItem.getName(); //上传的文件名
                        if(StringUtils.isNotEmpty(fileName)) {
				        //String contentType = fileItem.getContentType(); //上传的文件类型
				        //long sizeInBytes = fileItem.getSize(); //上传的文件的大小字节数
				        //System.out.println("fieldname:" + fieldName);
				        //System.out.println("fileName:" + fileName);
				        //System.out.println("contentType:" + contentType);
				        //System.out.println("sizeInBytes:" + sizeInBytes);

                        //获取文件存放目录的全路径名
                        String basePath= request.getSession().getServletContext().getRealPath("uploadfiles/SliderLogo");
                        //System.out.println("上传文件的存放路径："+ basePath);
				        //把文件写到目的地
				        //File fullFile = new File(fileName.getName());
				        String suffix = fileName.substring(fileName.lastIndexOf("."));
				        imgName = generateFileName() + suffix;
				        File uploadedFile = new File(basePath, imgName);
				        fileItem.write(uploadedFile);

                        sliderLogo.setPic(imgName);
                        }
                    }
				}
				System.out.println("上传成功!!!");

			} catch (FileUploadException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}

            this.sliderLogoJdbc.update(sliderLogo);

            /** 首页滑动Logo初始化 */
            Constants.sliderLogoList = sliderLogoJdbc.findAll(Constants.STATUS_ACTIVE);

            this.setRequest(Constants.MESSAGE, "修改滑动Logo成功。");
            this.redirect("/admin/article/sliderLogo-list.ac");
        }
    }

    public void status() throws Exception {
        String id = this.input("id");
        SliderLogo sliderLogo = this.sliderLogoJdbc.getById(Integer.valueOf(id));
        if (sliderLogo.getStatus() == 0) {
            sliderLogo.setStatus(1);
            this.setRequest(Constants.MESSAGE, "启用Logo成功。");
        } else {
            sliderLogo.setStatus(0);
            this.setRequest(Constants.MESSAGE, "禁用Logo成功。");
        }
        this.sliderLogoJdbc.update(sliderLogo);

        /** 首页滑动Logo初始化 */
        Constants.sliderLogoList = sliderLogoJdbc.findAll(Constants.STATUS_ACTIVE);

        this.redirect("/admin/article/sliderLogo-list.ac");
    }

    public void delete() throws Exception {
        String id = this.input("id");

        this.sliderLogoJdbc.deleteById(Integer.valueOf(id));

        /** 首页滑动Logo初始化 */
        Constants.sliderLogoList = sliderLogoJdbc.findAll(Constants.STATUS_ACTIVE);

        this.setRequest(Constants.MESSAGE, "删除Logo成功。");
        this.redirect("/admin/article/sliderLogo-list.ac");
    }


                    /**
	 * 使用当前时间值来产生一个唯一的文件名
	 * @return
	 */
	private static String generateFileName(){
		return new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
	}
}
